import { RedisClient, ClientOpts, createClient } from 'redis';

export class RedisHelper {
    redis: RedisClient;
    host: string;
    port: number;

    static instance: RedisHelper;

    constructor(host: string, port: number) {
        this.host = host;
        this.port = port;
    }

    /**
     * 实例化一个
     */
    static getInstance = (host: string, port: number): RedisHelper => {

        if (RedisHelper.instance === undefined) {
            RedisHelper.instance = new RedisHelper(host, port);
        }

        return RedisHelper.instance;
    }

    /**
     * 获取key值
     */
    getCacheValue = (cacheKey: string): Promise<any> => {
        const redis = createClient(this.port, this.host);

        return new Promise((resolve, reject) => {
            redis.get(cacheKey, (err, reply) => {
                if (err) {
                    return reject(err);
                }
                resolve(reply);
                this.closeClient(redis);
            });
        });
    }

    /**
     * 设置键值对
     */
    setCacheValue = (cacheKey: string, cacheValue: string): void => {
        const redis = createClient(this.port, this.host);
        redis.watch(cacheKey);
        const tx = redis.multi();
        tx.set(cacheKey, cacheValue);
        // tx.incrby
        tx.exec();
        // redis.incrby(cacheKey, Number.parseInt(cacheValue));
        this.closeClient(redis);
    }

    /**
     * 删除
     */
    deleteCacheValue = (cacheKey: string): void => {
        const redis = createClient(this.port, this.host);
        redis.del(cacheKey);
        this.closeClient(redis);
    }

    /**
     * 关闭连接
     */
    private closeClient = (redis: RedisClient): void => {
        if (redis.connected) {
            redis.end(true);
        }
    }

}
